const redis = require('redis');

const config = require('../config/config') 
// 实例redis对象
const client = redis.createClient({
  port: config.redis.port, 
  host: config.redis.host, 
  no_ready_check: true
});

//连接错误处理
client.on("error", err => {
  console.log('redis connect err', err);
});

client.on('connect', () => {
  console.log('redis connect success');
})

//验证redis
client.auth(config.redis.password);

const redisCache = {};

/**
 * redisCache setItem function
 * @param key
 * @param value
 * @param expire
 */
redisCache.setItem = (key, value, expire) => {
  return new Promise((resolve, reject) => {
    client.set(key, value, function (err, result) {

      if (err) {
        console.log(err);
        reject(err);
      }

      if (!isNaN(expire) && expire > 0) {
        client.expire(key, parseInt(expire));
      }
      resolve(result)
    })
  })
}

/**
 * redisCache getItem function
 * @param key
 */
redisCache.getItem = (key) => {
  return new Promise((resolve, reject) => {
    client.get(key, function (err, result) {
      if (err) {
        console.log(err);
        reject(err)
      }
      resolve(result)
    });
  })
}

module.exports = redisCache;
